<template>
  <div class="auth-modal-overlay" v-if="modelValue" @click="closeModal">
    <div class="auth-modal" @click.stop>
      <div class="auth-modal-header">
        <h3>{{ isLogin ? '用户登录' : '用户注册' }}</h3>
        <button class="close-btn" @click="closeModal">×</button>
      </div>
      
      <div class="auth-modal-body">
        <form @submit.prevent="handleSubmit">
          <div class="form-group">
            <label>用户名</label>
            <input 
              v-model="formData.username" 
              type="text" 
              placeholder="请输入用户名" 
              required 
            />
          </div>
          
          <div class="form-group">
            <label>密码</label>
            <input 
              v-model="formData.password" 
              type="password" 
              placeholder="请输入密码" 
              required 
            />
          </div>
          
          <div v-if="!isLogin" class="form-group">
            <label>确认密码</label>
            <input 
              v-model="formData.confirmPassword" 
              type="password" 
              placeholder="请再次输入密码" 
              required 
            />
          </div>
          
          <div v-if="error" class="error-message">
            {{ error }}
          </div>
          
          <button 
            type="submit" 
            class="submit-btn" 
            :disabled="loading"
          >
            {{ loading ? '处理中...' : (isLogin ? '登录' : '注册') }}
          </button>
        </form>
        
        <div class="auth-toggle">
          <span>
            {{ isLogin ? '还没有账户？' : '已有账户？' }}
            <a href="#" @click.prevent="toggleAuthMode">
              {{ isLogin ? '立即注册' : '立即登录' }}
            </a>
          </span>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive } from 'vue';
import { userLogin, userRegister } from '../api/userController';

const props = defineProps({
  modelValue: {
    type: Boolean,
    required: true
  }
});

const emit = defineEmits(['update:modelValue', 'login-success']);

const isLogin = ref(true);
const loading = ref(false);
const error = ref('');

const formData = reactive({
  username: '',
  password: '',
  confirmPassword: ''
});

const closeModal = () => {
  emit('update:modelValue', false);
};

const toggleAuthMode = () => {
  isLogin.value = !isLogin.value;
  error.value = '';
  // 清空表单
  formData.username = '';
  formData.password = '';
  formData.confirmPassword = '';
};

const handleSubmit = async () => {
  // 基本验证
  if (!formData.username || !formData.password) {
    error.value = '请填写所有必填字段';
    return;
  }

  if (!isLogin.value && formData.password !== formData.confirmPassword) {
    error.value = '两次输入的密码不一致';
    return;
  }

  loading.value = true;
  error.value = '';

  try {
    if (isLogin.value) {
      // 调用登录API
      const res = await userLogin({
        userName: formData.username,
        userPassword: formData.password
      });

      if (res.data.code === 0) {
          // 通知父组件登录成功
          emit('login-success', res.data.data);

          // 关闭模态框
          closeModal();
        } else {
          throw new Error(res.data.message || '登录失败');
        }
    } else {
      // 注册逻辑
      if (formData.password !== formData.confirmPassword) {
        error.value = '两次输入的密码不一致';
        return;
      }

      const res = await userRegister({
        userName: formData.username,
        userPassword: formData.password,
        checkPassword: formData.confirmPassword
      });

      if (res.data.code === 0) {
        // 注册成功后自动登录
        const loginRes = await userLogin({
          userName: formData.username,
          userPassword: formData.password
        });

        if (loginRes.data.code === 0) {
          emit('login-success', loginRes.data.data);
          closeModal();
        } else {
          throw new Error(loginRes.data.message || '自动登录失败');
        }
      } else {
        throw new Error(res.data.message || '注册失败');
      }
    }

    // 重置表单
    formData.username = '';
    formData.password = '';
    formData.confirmPassword = '';
  } catch (err: any) {
    error.value = err.message || (isLogin.value
        ? '登录失败，请检查用户名和密码'
        : '注册失败，请稍后重试');
  } finally {
    loading.value = false;
  }
};
</script>

<style scoped>
.auth-modal-overlay {
  position: fixed;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background-color: rgba(0, 0, 0, 0.6);
  display: flex;
  justify-content: center;
  align-items: center;
  z-index: 1000;
  padding: 2rem;
}

.auth-modal {
  background: white;
  border-radius: 20px;
  width: 100%;
  max-width: 480px;
  box-shadow: 0 20px 60px rgba(0, 0, 0, 0.15);
  overflow: hidden;
  animation: modalSlideIn 0.3s ease-out;
}

@keyframes modalSlideIn {
  from {
    opacity: 0;
    transform: translateY(-20px) scale(0.95);
  }
  to {
    opacity: 1;
    transform: translateY(0) scale(1);
  }
}

.auth-modal-header {
  padding: 2rem 2rem 1.5rem 2rem;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  color: white;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.auth-modal-header h3 {
  margin: 0;
  font-weight: 600;
  font-size: 1.4rem;
}

.close-btn {
  background: rgba(255, 255, 255, 0.1);
  border: none;
  color: white;
  font-size: 24px;
  cursor: pointer;
  padding: 0;
  width: 36px;
  height: 36px;
  display: flex;
  align-items: center;
  justify-content: center;
  border-radius: 50%;
  transition: all 0.3s ease;
}

.close-btn:hover {
  background: rgba(255, 255, 255, 0.2);
  transform: scale(1.1);
}

.auth-modal-body {
  padding: 2.5rem 2rem 2rem 2rem;
}

.form-group {
  margin-bottom: 1.8rem;
}

.form-group label {
  display: block;
  margin-bottom: 0.8rem;
  font-weight: 600;
  color: #333;
  font-size: 0.95rem;
}

.form-group input {
  width: 100%;
  padding: 1rem 1.2rem;
  border: 2px solid #e1e5e9;
  border-radius: 12px;
  font-size: 1rem;
  box-sizing: border-box;
  transition: all 0.3s ease;
  background: #f8f9fa;
}

.form-group input:focus {
  outline: none;
  border-color: #667eea;
  background: white;
  box-shadow: 0 0 0 3px rgba(102, 126, 234, 0.1);
}

.submit-btn {
  width: 100%;
  padding: 1rem 1.5rem;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  color: white;
  border: none;
  border-radius: 12px;
  font-size: 1.1rem;
  font-weight: 600;
  cursor: pointer;
  transition: all 0.3s ease;
  margin-top: 1rem;
}

.submit-btn:hover:not(:disabled) {
  transform: translateY(-2px);
  box-shadow: 0 8px 25px rgba(102, 126, 234, 0.3);
}

.submit-btn:disabled {
  opacity: 0.7;
  cursor: not-allowed;
}

.error-message {
  color: #e63946;
  background-color: #fef2f2;
  padding: 1rem 1.2rem;
  border-radius: 10px;
  margin-bottom: 1.5rem;
  font-size: 0.9rem;
  border: 1px solid #fecaca;
}

.auth-toggle {
  text-align: center;
  margin-top: 2rem;
  padding-top: 1.5rem;
  border-top: 1px solid #e1e5e9;
  font-size: 0.95rem;
  color: #666;
}

.auth-toggle a {
  color: #667eea;
  text-decoration: none;
  font-weight: 600;
  margin-left: 0.5rem;
  transition: color 0.3s ease;
}

.auth-toggle a:hover {
  color: #764ba2;
  text-decoration: underline;
}

@media (max-width: 768px) {
  .auth-modal-overlay {
    padding: 1rem;
  }
  
  .auth-modal {
    max-width: 100%;
    border-radius: 16px;
  }
  
  .auth-modal-header {
    padding: 1.5rem 1.5rem 1rem 1.5rem;
  }
  
  .auth-modal-body {
    padding: 2rem 1.5rem 1.5rem 1.5rem;
  }
}
</style>